﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.Generic;
using exsportance.Silverlight.Common.Utils;
using System.Globalization;

namespace exsportance.Silverlight.Validate.Validators
{
    /// <summary>
    /// Validator that returns true if value is less than a max value
    /// </summary>
    public class LessThanValidator<T> : BaseValidator where T : IComparable<T>
    {
        #region members
        /// <summary>
        /// Validation failure message key for when the value is not less than min
        /// </summary>
        private const string NOT_LESS = "notLessThan";

        /// <summary>
        /// Validation failure message key for when the value is not the right type
        /// </summary>
        private const string NOT_TYPE = "notType";

        protected Dictionary<string, string> _messagesTemplates = new Dictionary<string, string>(){
        {LessThanValidator<T>.NOT_LESS,"'%value%' is not less than '%max%'"},
        {LessThanValidator<T>.NOT_TYPE,"'%value%' is not type of '%inputtype%'"},
        };

        #endregion

        #region properties
        /// <summary>
        /// Maximum value
        /// </summary>
        public T Max { get; set; }

        /// <summary>
        /// Input type
        /// </summary>
        public string InputType { get { return typeof(T).Name; } }
        #endregion

        #region constructor
        public LessThanValidator(T max)
            : base()
        {
            Max = max;
        }

        #endregion

        #region protected methods
        /// <summary>
        /// Returns true if if value is greater than min
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        protected override bool CheckValid(object value)
        {
            rememberValue(value);
            T convertedValue = default(T);

            try
            {
                convertedValue = (T)Convert.ChangeType(value, typeof(T), CultureInfo.CurrentCulture.NumberFormat);
            }
            catch
            {
                raiseMessage(LessThanValidator<T>.NOT_TYPE);
                return false;
            }

            if (convertedValue.CompareTo(Max) >= 0)
            {
                raiseMessage(LessThanValidator<T>.NOT_LESS);
                return false;
            }
            return true;
        }


        protected override System.Collections.Generic.Dictionary<string, string> getMessageTemplates()
        {
            return _messagesTemplates;
        }
        #endregion
    }
}
